
from whiff import resolver
from whiff import whiffenv
from whiff.middleware import misc
from whiff.rdjson import jsonParse
import getwords

class getCompletionInfo(misc.utility):
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        searchInput = whiffenv.cgiGet(env, "searchInput", "")
        words = searchInput.split()
        wordPrefix = wordValue = ""
        if words:
            wordValue = words[-1].lower()
            otherwords = words[:-1]
            wordPrefix = " ".join(otherwords)
            if wordPrefix:
                wordPrefix += " "
        wordGetter = getwords.wordsGetter("/tmp/words")
        wordMatches = wordGetter.getWordsNear(wordValue)
        searchMatches = [wordPrefix + w for w in wordMatches]
        start_response("200 OK", [('Content-Type', 'application/javascript')])
        yield "completionsInfo = "
        yield jsonParse.format(searchMatches)
        yield ";\n"

__middleware__ = getCompletionInfo
